import api from '../api'
const state = {
  tabList: [], // 一级标签
  activeTab: null, // 当前激活的标签
  activeFeature: null,
  activeChildTab: null, // 二级标签
  activeChildTabId: null
}

const getters = {
  tabList: state => state.tabList,
  allTabList: state => {
    let arr = [];
    state.tabList.forEach(tab => {
      arr.push(tab);
      if (tab.childs && tab.childs.length > 0) {
        tab.childs.forEach(t => {
          arr.push({ ...t,
            parentTab: tab.id
          })
        })
      }
    });
    return arr;
  },
  activeTab: state => {
    if (state.activeTab != null) {
      return state.activeTab;
    } else if (state.tabList.length > 0) {
      return state.tabList[0];
    } else {
      return null
    }
  },
  activeFeature: state => state.activeFeature,
  activeChildTab: (state, getters) => {
    let tab = getters.activeTab;
    if (tab == null || tab.childs == null || tab.childs.length == 0) return null;
    if (state.activeChildTabId == null) return tab.childs[0];
    let activeTab = tab.childs.find(t => t.id == state.activeChildTabId);
    if (activeTab == null) return tab.childs[0];
    return activeTab;
  },
  selectTab: (state, getters) => {
    if (getters.activeChildTab != null) return getters.activeChildTab;
    return getters.activeTab;
  }
}

const mutations = {
  // 初始化tabList
  setTabList(state, list) {
    state.tabList = list;
  },
  // 切换tab
  selectTab(state, tabId) {
    let tab = state.tabList.find(t => t.id == tabId);
    state.activeTab = tab;
  },
  setActiveFeature(state, feature) {
    state.activeFeature = feature;
  },
  setActiveChildTab(state, name) {
    const tab = state.activeTab.child.find(t => t.id == name);
    state.activeChildTab = tab;
  },
  setActiveChildTabId(state, id) {
    state.activeChildTabId = id;
  }
}

const actions = {
  async getTabList(context) {
    let rst = await api.getTabList();
    return new Promise(resolve => {
      if (rst.success) {
        context.commit('setTabList', rst.data)
      }
      resolve(rst)
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
